package com.example.rabc.controller;

import com.example.rabc.common.ApiResponse;
import com.example.rabc.dto.LoginRequest;
import com.example.rabc.dto.UserCreateRequest;
import com.example.rabc.entity.User;
import com.example.rabc.service.UserService;
import com.example.rabc.util.JwtUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 密码编码器
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 注册用户
     * @param request 用户创建请求
     * @return 注册成功的用户
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> register(@RequestBody UserCreateRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setEmail(request.getEmail());
        user.setRealName(request.getRealName());
        
        User createdUser = userService.createUser(user, request.getRoleCodes());
        return ResponseEntity.ok(ApiResponse.success(createdUser));
    }

    /**
     * 登录用户
     * @param loginRequest 登录请求
     * @return 登录成功的用户和JWT token
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 认证用户
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );
            // 设置认证信息到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 生成JWT token
            String token = jwtUtil.generateToken(loginRequest.getUsername());
            
            // 准备响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("username", loginRequest.getUsername());
            
            User user = userService.getUserByUsername(loginRequest.getUsername());
            responseData.put("user", user);
            
            return ResponseEntity.ok(ApiResponse.success(responseData));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("用户名或密码错误"));
        }
    }
    

}